Completed
Push — development ( 913dac...56a9ad )
by Nils
13:17
created

post(ꞌsources/items.queries.phpꞌ)   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 2
nop 1
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
1
/**
2
 * @file          functions.js
3
 * @author        Nils Laumaillé
4
 * @version       2.1.27
5
 * @copyright     (c) 2009-2017 Nils Laumaillé
6
 * @licensing     GNU AFFERO GPL 3.0
7
 * @link          http://www.teampass.net
8
 *
9
 * This library is distributed in the hope that it will be useful,
10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
 */
13
14
/**
15
*   Show or hide Loading animation GIF
16
**/
17
function LoadingPage(){
18
    if ($("#div_loading").is(":visible")) {
19
        $("#div_loading").addClass("hidden");
20
    } else {
21
        $("#div_loading").removeClass("hidden");
22
    }
23
}
24
25
26
/**
27
*   Add 1 hour to session duration
28
**/
29
function IncreaseSessionTime(messageEnd, messageWait, duration){
30
    duration = duration || 60;
31
    $("#main_info_box_text").html(messageWait);
32
    $("#main_info_box").show().position({
33
        my: "center",
34
        at: "center top+75",
35
        of: "#top"
36
    });
37
    $.post(
38
        "sources/main.queries.php",
39
        {
40
        type    : "increase_session_time",
41
        duration: parseInt(duration) * 60
42
        },
43
        function(data){
44
            if (data[0].new_value !== "expired") {
45
                $("#main_info_box_text").html(messageEnd);
46
                $("#main_info_box").show(1).delay(3000).fadeOut(1000)
47
                $("#temps_restant").val(data[0].new_value);
48
                $("#date_end_session").val(data[0].new_value);
49
                $("#countdown").css("color","white");
50
                $("#div_increase_session_time").dialog("close");
51
            } else {
52
                $(location).attr('href',"index.php?session=expired");
53
            }
54
        },
55
        "json"
56
    );
57
}
58
59
/**
60
*   Countdown before session expiration
61
**/
62
function countdown()
63
{
64
    var DayTill;
65
    var theDay =  $("#temps_restant").val();
66
    var today = new Date(); //Create an Date Object that contains today's date.
67
    var second = Math.floor(theDay - (today.getTime()/1000));
68
    var minute = Math.floor(second/60); //Devide "second" into 60 to get the minute
69
    var hour = Math.floor(minute/60); //Devide "minute" into 60 to get the hour
70
    var CHour= hour % 24; //Correct hour, after devide into 24, the remainder deposits here.
71
    if (CHour<10) {
72
        CHour = "0" + CHour;
73
    }
74
    var CMinute= minute % 60; //Correct minute, after devide into 60, the remainder deposits here.
75
    if (CMinute<10) {
76
        CMinute = "0" + CMinute;
77
    }
78
    var CSecond= second % 60; //Correct second, after devide into 60, the remainder deposits here.
79
    if (CSecond<10) {
80
        CSecond = "0" + CSecond;
81
    }
82
    DayTill = CHour+":"+CMinute+":"+CSecond;
83
84
    //Avertir de la fin imminante de la session
85
    if (DayTill === "00:01:00") {
86
        $("#div_increase_session_time").dialog("open");
87
        $("#countdown").css("color","red");
88
    }
89
90
    // Manage end of session
91
    if ($("#temps_restant").val() !== "" && DayTill <= "00:00:00" && $("#please_login").val() !== "1") {
92
        $("#please_login").val("1");
93
        $(location).attr('href',"index.php?session=expired");
94
    }
95
96
    //Rewrite the string to the correct information.
97
    if ($("#countdown")) {
98
        $("#countdown").html(DayTill); //Make the particular form chart become "Daytill"
99
    }
100
101
    //Create the timer "counter" that will automatic restart function countdown() again every second.
102
    $(this).delay(1000).queue(function() {
103
        $(this).hide();
104
        countdown();
105
        $(this).dequeue();
106
    });
107
}
108
109
/**
110
*   Open a dialog
111
**/
112
function OpenDialog(id){
113
    $("#"+id).dialog("open");
114
}
115
116
/**
117
*   Toggle a DIV
118
**/
119
function toggleDiv(id){
120
    $("#"+id).slideToggle("slow");
121
    //specific case to not show upgrade alert
122
    if(id === "div_maintenance"){
123
        $.post(
124
            "sources/main.queries.php",
125
            {
126
                type    : "hide_maintenance"
127
            }
128
        );
129
    }
130
}
131
132
/**
133
*   Checks if value is an integer
134
**/
135
function isInteger(s) {
136
  return (s.toString().search(/^-?[0-9]+$/) === 0);
137
}
138
139
/**
140
*   Generate a random string
141
**/
142
function CreateRandomString(size,type){
143
    var chars = "";
144
145
    // CHoose what kind of string we want
146
    if (type === "num") {
147
        chars = "0123456789";
148
    } else if (type === "num_no_0") {
149
        chars = "123456789";
150
    } else if (type === "alpha") {
151
        chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
152
    } else if (type === "secure") {
153
        chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz&#@;!+-$*%";
154
    } else {
155
        chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
156
    }
157
158
    //generate it
159
    var randomstring = "";
160
    for (var i=0; i<size; i++) {
161
        var rnum = Math.floor(Math.random() * chars.length);
162
        randomstring += chars.substring(rnum,rnum+1);
163
    }
164
165
    //return
166
    return randomstring;
167
}
168
169
170
/**
171
*
172
**/
173
function unsanitizeString(string){
174
    if(string !== "" && string !== null){
175
        string = string.replace(/\\/g,"").replace(/&#92;/g,"\\");
176
    }
177
    return string;
178
}
179
180
/**
181
*   Clean up a string and delete any scripting tags
182
**/
183
function sanitizeString(string){
184
    if(string !== "" && string !== null) {
185
        string = string.replace(/\\/g,"&#92;").replace(/"/g,"&quot;");
186
        string = string.replace(new RegExp("\\s*<script[^>]*>[\\s\\S]*?</script>\\s*","ig"), "");
187
    }
188
    return string;
189
}
190
191
/**
192
*   Send email
193
**/
194
function SendMail(category, contentEmail, keySent, message){
195
    $.post(
196
        "sources/items.queries.php",
197
        {
198
            type    : "send_email",
199
            cat     : category,
200
            content : contentEmail,
201
            key     : keySent
202
        },
203
        function(data){
204
            if (typeof data[0].error !== "undefined" && data[0].error !== "") {
205
                message = data[0].message;
206
            }
207
            $("#div_dialog_message_text").html(message);
208
            $("#div_dialog_message").dialog("open");
209
        },
210
        "json"
211
    );
212
}
213
214
/**
215
*   Checks if email has expected format ([email protected])
216
**/
217
function IsValidEmail(email){
218
    var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
219
    return filter.test(email);
220
}
221
222
/**
223
*   Checks if URL has expected format
224
**/
225
function validateURL(textval) {
226
    //var urlregex = new RegExp("^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}([0-9A-Za-z]+\.)");
227
    var urlregex = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
228
    return urlregex.test(textval);
229
}
230
231
232
function split( val ) {
233
    return val.split( / \s*/ );
234
}
235
236
function extractLast( term ) {
237
    return split( term ).pop();
238
}
239
240
241
function storeError(messageError, dialogDiv, textDiv){
242
    //Store error in DB
243
    $.post(
244
        "sources/main.queries.php",
245
        {
246
            type    : "store_error",
247
            error   : escape(messageError)
248
        }
249
    );
250
    //Display
251
    $("#"+textDiv).html("An error appears. Answer from Server cannot be parsed!<br />Returned data:<br />"+messageError);
252
    $("#"+dialogDiv).dialog("open");
253
}
254
255
/**
256
 * [aesEncrypt description]
257
 * @param  {[type]} text [description]
258
 * @param  {[type]} key  [description]
259
 * @return {[type]}      [description]
260
 */
261
function aesEncrypt(text, key)
262
{
263
    return Aes.Ctr.encrypt(text, key, 256);
264
}
265
266
/**
267
 * [aesDecrypt description]
268
 * @param  {[type]} text [description]
269
 * @param  {[type]} key  [description]
270
 * @return {[type]}      [description]
271
 */
272
function aesDecrypt(text, key)
273
{
274
    return Aes.Ctr.decrypt(text, key, 256);
275
}
276
277
/**
278
 * Shows error message
279
 * @param  {string} message  Message to display
280
 * @return {boolean}         False
281
 */
282
function jsonErrorHdl(message)
283
{
284
    $("#div_dialog_message_text").html(message);
285
    $("#div_dialog_message").dialog("open");
286
    $("#items_path_var").html('<i class="fa fa-folder-open-o"></i>&nbsp;Error');
287
    $("#items_list_loader").addClass("hidden");
288
    return false;
289
}
290
291
/**
292
 * [prepareExchangedData description]
293
 * @param  {[type]} data [description]
294
 * @param  {[type]} type [description]
295
 * @param  {[type]} key  [description]
296
 * @return {[type]}      [description]
297
 */
298
function prepareExchangedData(data, type, key)
299
{
300
    var jsonResult;
0 ignored issues
show
Unused Code introduced by
The variable jsonResult seems to be never used. Consider removing it.
Loading history...
301
    if (type === "decode") {
302
        if ($("#encryptClientServer").val() === "0") {
303
            try {
304
                return $.parseJSON(data);
305
            }
306
            catch (e) {
307
                return "Error: " + jsonErrorHdl(e);
308
            }
309
        } else {
310
            try {
311
                return $.parseJSON(aesDecrypt(data, key));
312
            }
313
            catch (e) {
314
                return "Error: " + jsonErrorHdl(e);
315
            }
316
        }
317
    } else if (type === "encode") {
318
        if ($("#encryptClientServer").val() === "0") {
319
            return data;
320
        } else {
321
            return aesEncrypt(data, key);
322
        }
323
    } else {
324
        return false;
325
    }
326
}
327
328
/**
329
 * Show a message to the user on top of the screen
330
 * @param  {[type]} textToDisplay [description]
331
 * @return {[type]}               [description]
332
 */
333
function displayMessage(textToDisplay)
334
{
335
    $("#main_info_box_text").html(textToDisplay);
336
    $("#main_info_box").show().position({
337
        my: "center",
338
        at: "center top+20",
339
        of: "#main_simple"
340
    });
341
    setTimeout(
342
        function(){
343
            $("#main_info_box").effect( "fade", "slow");
344
        },
345
        2000
346
    );
347
}
348
349
/**
350
 * Make blinking an HMLT element
351
 * @param  {[type]} elem  [description]
352
 * @param  {[type]} times [description]
353
 * @param  {[type]} speed [description]
354
 * @param  {[type]} klass [description]
355
 * @return {[type]}       [description]
356
 */
357
function blink(elem, times, speed, klass)
358
{
359
    if (times > 0 || times < 0) {
360
        if ($(elem).hasClass(klass)) {
361
            $(elem).removeClass(klass);
362
        } else {
363
            $(elem).addClass(klass);
364
        }
365
    }
366
367
    clearTimeout(function() { blink(elem, times, speed, klass); });
368
369
    if (times > 0 || times < 0) {
370
        $(this).delay(speed).queue(function() {
371
            $(this).hide();
372
            blink(elem, times, speed, klass);
373
            $(this).dequeue();
374
        });
375
        times-= .5;
376
    }
377
}